import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class monyBingQueue {

    private static final String EXCHANGE_NAME = "direct_logs";

    private static String queueName = "disk";

    public static void main(String[] argv) throws Exception {
       new Thread(()-> {
            try {
                queue1();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

       new Thread(()->{
           try {
               queue2();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }).start();
    }


    public static void queue1() throws IOException {
        Channel channel = RabbitMQUtils.getFactory();

        //声明exchange
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        //声明队列
        channel.queueDeclare(queueName, false, false, false, null);
        //将一个队列绑定到exchange,error 是key
        channel.queueBind(queueName, EXCHANGE_NAME, "error");
        System.out.println(queueName + "等待接收消息.....");
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            message = queueName + "接收绑定键:" + delivery.getEnvelope().getRoutingKey() + ",消息:" + message;
            File file = new File("D:\\java_project\\items\\spring_test\\rabbitMQ_test\\rabbitMQ-client\\src\\main\\resources\\errorLos.txt");
            FileUtils.writeStringToFile(file, message, "UTF-8");
            System.out.println(queueName + "错误日志已经接收");
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
            // 取消回调
        });
    }

    public static void queue2() throws IOException {
        Channel channel = RabbitMQUtils.getFactory();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        String queueName = "console";
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, EXCHANGE_NAME, "info");
        channel.queueBind(queueName, EXCHANGE_NAME, "warning");
        System.out.println(queueName + "等待接收消息.....");
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(queueName + " 接收绑定键 :" + delivery.getEnvelope().getRoutingKey() + ", 消 息:" + message);
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
        });
    }
}